package com.lwl.blue.commont.config;

import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.lwl.blue.commont.base.BizException;
import com.lwl.blue.commont.base.ErrorCode;
import com.lwl.blue.commont.base.JsonResult;
import org.apache.ibatis.exceptions.PersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p> 异常统一处理类 </p>
 *
 * @Date: 2021/11/20 08:38
 * @version: V1.0
 * @Decription:
 * @author: 蓝文良
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = {BizException.class})
    @ResponseBody
    public JsonResult bizExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("发生业务异常！原因是：{}", e.getMessage());
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(e.getCode());
        jsonResult.setMsg(e.getMessage());
        return jsonResult;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public JsonResult argumentValidHandler(HttpServletRequest req, Exception e) {

        JsonResult result = new JsonResult();
        List<String> errorList = new ArrayList<>();
        List<ObjectError> allErrors = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors();
        for (ObjectError error : allErrors) {
            errorList.add(error.getDefaultMessage());
        }
        result.setCode(ErrorCode.ARGUMENT_NOT_VALID.getCode());
        result.setMsg(StringUtils.join(errorList, "<br/>"));
        return result;
    }

    /**
     * 处理空指针的异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public JsonResult exceptionHandler(HttpServletRequest req, NullPointerException e) {
        logger.error("发生空指针异常！原因是:", e);
        return new JsonResult().error("空指针异常：数据缺失");
    }


    public GlobalExceptionHandler() {
        super();
    }

    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonResult exceptionHandler(HttpServletRequest req, Exception e) {
        if (Objects.nonNull(e.getCause()) && Objects.nonNull(e.getCause().getCause())) {
            if (e.getCause().getCause() instanceof BizException) {
                BizException bizException = (BizException) e.getCause().getCause();
                JsonResult jsonResult = new JsonResult();
                jsonResult.setCode(bizException.getCode());
                jsonResult.setMsg(bizException.getMessage());
                return jsonResult;
            }
        }
        logger.error("未知异常！原因是:{},messsage:{}", e, e.getMessage());
        return new JsonResult().error("系统异常，请联系系统管理员：<br/>"+e.getMessage().substring(0,e.getMessage().length()>1000?1000:e.getMessage().length()));
    }
}
